//
//  MemberTrackView.m
//  location
//
//  Created by Dongxiang Xu on 2024/5/11.
//


#import "XDXBaseTabBarViewController.h"
#import "RegionSettingViewController.h"
#import "MemberTrackView.h"
#import "CashViewController.h"
#import "TrackMapTableViewCell.h"
#import "TrackStaticTableViewCell.h"
#import "XDXMapView.h"
#import "HitTouchView.h"
#import "RouteAnnotationView.h"
#import "TrackEventAnnotationView.h"
#import "UIImageView+WebCache.h"

#define orginHeight 253
@interface MemberTrackView ()<UITableViewDataSource,UITableViewDelegate,UIGestureRecognizerDelegate,MKMapViewDelegate>

@property (nonatomic, strong) NSDictionary *info;
@property (nonatomic, strong) NSDictionary *groupInfo;
@property (nonatomic, strong) UILabel *nickTime;
@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) UIView *topView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView *bgView;
@property (nonatomic, strong) NSMutableArray *tableList;
@property (nonatomic, strong) UIImageView *avatar;
@property (nonatomic, strong) UILabel *nickName;
@property (nonatomic, strong) UILabel *lastLog;
@property (nonatomic, strong) UILabel *time;
@property (nonatomic, strong) XDXMapView *mapView;
@property (nonatomic, strong) NSMutableDictionary *mapImageLoadDic;

@end

@implementation MemberTrackView

- (instancetype)initWithFrame:(CGRect)frame
                         Info:(NSDictionary *)info
                    GroupInfo:(NSDictionary *)groupInfo
{
    self = [super initWithFrame:frame];
    if (self) {
        self.layer.masksToBounds = YES;
        _info = info;
        _groupInfo = groupInfo;
        _mapImageLoadDic = [NSMutableDictionary dictionary];
        [self initUI];
    }
    return self;
}

- (void)drawMapImageWithInfo:(NSMutableDictionary *)info
{
    NSString *key = [NSString stringWithFormat:@"%@ - %@",[info[@"array"] firstObject][@"create_time"],[info[@"array"] lastObject][@"create_time"]];
    if (![_mapImageLoadDic.allKeys containsObject:key]) {
        [_mapImageLoadDic setValue:info forKey:key];
    }
    if (!self.mapView) {
        self.mapView = [[XDXMapView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH, 0, SCREEN_WIDTH-32, (SCREEN_WIDTH-32)*0.3838+3)];
        self.mapView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        self.mapView.delegate = self;
        self.mapView.rotateEnabled = NO;
        self.mapView.zoomLevel = 15;
        self.mapView.mapType = MKMapTypeStandard;
        [self addSubview:self.mapView];
        
        if (![info[@"image"] isKindOfClass:[UIImage class]]) {
            CLLocationCoordinate2D satrtCoord = CLLocationCoordinate2DMake([[info[@"array"] firstObject][@"latitude"] doubleValue],[[info[@"array"] firstObject][@"longtitude"] doubleValue]);
            MKPointAnnotation *startAnnotation = [[MKPointAnnotation alloc] init];
            startAnnotation.coordinate = satrtCoord;
            startAnnotation.title    = @"start";
            startAnnotation.subtitle = @"start";
            [self.mapView addAnnotation:startAnnotation];
            
            CLLocationCoordinate2D endCoord = CLLocationCoordinate2DMake([[info[@"array"] lastObject][@"latitude"] doubleValue],[[info[@"array"] lastObject][@"longtitude"] doubleValue]);
            MKPointAnnotation *endAnnotation = [[MKPointAnnotation alloc] init];
            endAnnotation.coordinate = endCoord;
            endAnnotation.title    = @"end";
            endAnnotation.subtitle = @"end";
            [self.mapView addAnnotation:endAnnotation];
            
            CLLocationCoordinate2D *runningCoords = (CLLocationCoordinate2D *)malloc([info[@"array"] count] * sizeof(CLLocationCoordinate2D));
            for (int i = 0; i < [info[@"array"] count]; i++)
            {
                @autoreleasepool
                {
                    NSDictionary *data = info[@"array"][i];
                    runningCoords[i].latitude = [data[@"latitude"] doubleValue];
                    runningCoords[i].longitude = [data[@"longtitude"] doubleValue];
                }
            }
            
            MKPolyline *polyline = [MKPolyline polylineWithCoordinates:runningCoords count:[info[@"array"] count]];
            [self.mapView addOverlay:polyline];
            const CGFloat screenEdgeInset = 20;
            UIEdgeInsets inset = UIEdgeInsetsMake(screenEdgeInset, screenEdgeInset, screenEdgeInset, screenEdgeInset);
            [self.mapView setVisibleMapRect:polyline.boundingMapRect edgePadding:inset animated:NO];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                UIImage *image = [self captureView:self.mapView];
                [info setValue:image forKey:@"image"];
                [self.mapView removeFromSuperview];
                self.mapView = nil;
                [self.mapImageLoadDic removeObjectForKey:key];

                [self.tableView reloadData];
            });
        }
    }
}

- (UIImage *)captureView:(UIView *)view
{
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.isOpaque, 0.0);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
    if ([annotation.title isEqualToString:@"end"]) {
        static NSString *customReuseIndetifier = @"RouteAnnotationView";
        RouteAnnotationView *annotationView = (RouteAnnotationView* )[mapView dequeueReusableAnnotationViewWithIdentifier:customReuseIndetifier];
        
        if (annotationView == nil)
        {
            annotationView = [[RouteAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:customReuseIndetifier];
            annotationView.canShowCallout = NO;
            annotationView.draggable = NO;
            annotationView.locationImg.image = [UIImage imageNamed:@"dingwei-4"];
        }

        return annotationView;
    }else if ([annotation.title isEqualToString:@"start"]){
        static NSString *customReuseIndetifier = @"TrackEventAnnotationView";
        TrackEventAnnotationView *annotationView = (TrackEventAnnotationView* )[mapView dequeueReusableAnnotationViewWithIdentifier:customReuseIndetifier];
        
        if (annotationView == nil)
        {
            annotationView = [[TrackEventAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:customReuseIndetifier];
            annotationView.canShowCallout = NO;
            annotationView.draggable = NO;
        }
        annotationView.subLayer.backgroundColor = RealBlackColor.CGColor;
        annotationView.mapImg.backgroundColor = RealWhiteColor;
        
        return annotationView;
    }else{
        return nil;
    }
}

#pragma mark - mapview delegate
- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id <MKOverlay>)overlay
{
    MKPolylineRenderer *polylineRenderer = [[MKPolylineRenderer alloc] initWithOverlay:overlay];
    polylineRenderer.lineWidth = 6.f;
    polylineRenderer.strokeColor =  NormalMainColor;
    return polylineRenderer;
}

- (void)initUI
{
    _headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, self.tableView.height-orginHeight+121)];
    _headerView.layer.masksToBounds = YES;
    
    HitTouchView *view = [[HitTouchView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, self.tableView.height-orginHeight)];
    [_headerView addSubview:view];
    
    UIView *topView = [[UIView alloc] initWithFrame:CGRectMake(0, _headerView.height-121, SCREEN_WIDTH, 121)];
    [_headerView addSubview:topView];
    CALayer *infoLayer = [CALayer layer];
    infoLayer.frame = topView.bounds;
    infoLayer.cornerRadius = 25;
    infoLayer.masksToBounds = NO;
    infoLayer.backgroundColor = RealWhiteColor.CGColor;
    infoLayer.shadowColor = RealBlackColor.CGColor;
    infoLayer.shadowOffset = CGSizeMake(0,2);
    infoLayer.shadowOpacity = 0.3;
    infoLayer.shadowRadius = 3;
    [topView.layer addSublayer:infoLayer];
    
        
    _topView = [[UIView alloc] initWithFrame:CGRectMake(0, _headerView.height-121, SCREEN_WIDTH, 121)];
    _topView.backgroundColor = RealWhiteColor;
    [_headerView addSubview:_topView];
    UIBezierPath *cornerRadiusPath =
    [UIBezierPath bezierPathWithRoundedRect:self.topView.bounds
                          byRoundingCorners:UIRectCornerTopRight | UIRectCornerTopLeft
                                cornerRadii:CGSizeMake(25, 25)];
    
    CAShapeLayer *cornerRadiusLayer = [CAShapeLayer layer];
    cornerRadiusLayer.frame = self.topView.bounds;
    cornerRadiusLayer.path = cornerRadiusPath.CGPath;
    self.topView.layer.mask = cornerRadiusLayer;
        
    UILabel *slider = [[UILabel alloc] initWithFrame:CGRectMake((SCREEN_WIDTH-42)/2, 8, 42, 4)];
    slider.layer.masksToBounds = YES;
    slider.backgroundColor = GraryMiddleColor;
    [slider.layer setCornerRadius:2];
    [_topView addSubview:slider];
    
    _avatar = [[UIImageView alloc] initWithFrame:CGRectMake(16, 32, 60, 60)];
    _avatar.layer.masksToBounds = YES;
    [_avatar.layer setCornerRadius:24];
    _avatar.backgroundColor = GraryLightColor;
    [_avatar sd_setImageWithURL:[NSURL URLWithString:_info[@"avatar"]]];
    [_topView addSubview:_avatar];
    
    _nickName = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(_avatar.frame)+16, 31, SCREEN_WIDTH-CGRectGetMaxX(_avatar.frame)-32, 24)];
    _nickName.font = MEDIUM_FONT(15);
    _nickName.textColor = RealBlackColor;
    if ([_info[@"remark"] isKindOfClass:[NSString class]] && [_info[@"remark"] length]>0) {
        _nickName.text = [NSString stringWithFormat:@"%@",_info[@"remark"]];
    }else{
        if ([_info[@"nickName"] isKindOfClass:[NSString class]] && [_info[@"nickName"] length]>0) {
            _nickName.text = [NSString stringWithFormat:@"%@",_info[@"nickName"]];
        }else{
            _nickName.text = @"";
        }
    }
    [_topView addSubview:_nickName];
    
    _lastLog = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(_avatar.frame)+16, CGRectGetMaxY(_nickName.frame)+4, SCREEN_WIDTH-CGRectGetMaxX(_avatar.frame)-32, 16)];
    _lastLog.textColor = GraryHeavyLightColor;
    _lastLog.font = DEFAULT_FONT(14);
    [_topView addSubview:_lastLog];
    
    _time = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(_avatar.frame)+16, CGRectGetMaxY(_lastLog.frame)+2, SCREEN_WIDTH-CGRectGetMaxX(_avatar.frame)-32, 16)];
    _time.textColor = GraryTooHeavyColor;
    _time.font = DEFAULT_FONT(14);
    [_topView addSubview:_time];
    
    if ([_info[@"logout"] integerValue]==1) {
        _lastLog.textColor = RedColor;
        _lastLog.text = @"网络异常或手机关机";
        
    }else if ([_info[@"lastlog"] isKindOfClass:[NSString class]] && [_info[@"lastlog"] length]>0) {
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        dateFormatter.locale = [NSLocale systemLocale];
        dateFormatter.calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierISO8601];
        NSDate *firstDate = [dateFormatter dateFromString:[[_info[@"timestamp"] substringToIndex:19] stringByReplacingOccurrencesOfString:@"T" withString:@" "]];
        NSInteger firstSecond = [firstDate timeIntervalSince1970];
                        
        if (![_info[@"activity"] containsString:@"静止"]) {
            if ([_info[@"lastlog"] isKindOfClass:[NSString class]] && [_info[@"lastlog"] length]>0 && ([[XDXTimeTool getNowTimeTimestamp] integerValue]-firstSecond)>300) {
                _lastLog.text = [NSString stringWithFormat:@"%@ 附近",_info[@"lastlog"]];
                _time.hidden = NO;
            }else{
                _lastLog.text = [NSString stringWithFormat:@"%@ 至 %@",[_info[@"activity"] isEqualToString:@"行程"]?@"步行":_info[@"activity"],_info[@"lastlog"]];
                _time.hidden = YES;
            }
        }else{
            _lastLog.text = [NSString stringWithFormat:@"%@ 附近",_info[@"lastlog"]];
            _time.hidden = NO;
        }
    }
    
    self.tableView.tableHeaderView = _headerView;
    [self addSubview:self.tableView];
    
    self.bgView = [[UIView alloc] initWithFrame:CGRectMake(0, self.height, SCREEN_WIDTH, self.height)];
    self.bgView.backgroundColor = RealWhiteColor;
    [self insertSubview:self.bgView belowSubview:self.tableView];
        
    UIView *navView = [[UIView alloc] initWithFrame:CGRectMake(0, -NAVHEIGHT, SCREEN_WIDTH, NAVHEIGHT)];
    [self addSubview:navView];
    
    UIVisualEffectView *visualEffect = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleExtraLight]];
    visualEffect.frame = CGRectMake(0, 0, navView.width, navView.height);
    [navView addSubview:visualEffect];
        
    UIButton *pop = [[UIButton alloc] initWithFrame:CGRectMake(2, STATUSHEIGHT, 44, 44)];
    [pop setImage:[UIImage imageNamed:@"login_back_nor"] forState:UIControlStateNormal];
    [navView addSubview:pop];
    [[pop rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [self dismiss];
    }];
    
    UILabel *nickName = [[UILabel alloc] initWithFrame:CGRectMake(0, STATUSHEIGHT, SCREEN_WIDTH, 24)];
    nickName.textAlignment = NSTextAlignmentCenter;
    nickName.font = MEDIUM_FONT(16);
    nickName.textColor = RealBlackColor;    
    if ([_info[@"remark"] isKindOfClass:[NSString class]] && [_info[@"remark"] length]>0) {
        nickName.text = [NSString stringWithFormat:@"%@",_info[@"remark"]];
    }else{
        if ([_info[@"nickName"] isKindOfClass:[NSString class]] && [_info[@"nickName"] length]>0) {
            nickName.text = [NSString stringWithFormat:@"%@",_info[@"nickName"]];
        }else{
            nickName.text = @"";
        }
    }
    [navView addSubview:nickName];
    
    _nickTime = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(nickName.frame)+2, SCREEN_WIDTH, 16)];
    _nickTime.textAlignment = NSTextAlignmentCenter;
    _nickTime.font = DEFAULT_FONT(12);
    _nickTime.textColor = GraryTooHeavyColor;
    [navView addSubview:_nickTime];
    
    UIImageView *line = [[UIImageView alloc] initWithFrame:CGRectMake(0, NAVHEIGHT-1, SCREEN_WIDTH, 1)];
    line.image = [UIImage imageNamed:@"line"];
    [navView addSubview:line];
    
    [UIView animateWithDuration:0.3 animations:^{
        navView.y = 0;       
    }];
    self.tableView.y = NAVHEIGHT;
    self.bgView.y = self.height-orginHeight+121;
}

- (void)dismiss
{
    UIImpactFeedbackGenerator *feedBackGenertor = [[UIImpactFeedbackGenerator alloc] initWithStyle:UIImpactFeedbackStyleLight];
    [feedBackGenertor impactOccurred];
    self.bgView.alpha = 0;
    [UIView animateWithDuration:0.3 animations:^{
        self.tableView.y = self.height;
        self.bgView.y = self.height;
    }];
    if (self.MemberTrackPopBlock) {
        self.MemberTrackPopBlock();
    }
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.tableList.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if ([self.tableList[section][@"isShow"] boolValue]) {
        return [self.tableList[section][@"array"] count];
    }else{
        return 0;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self.tableList[indexPath.section][@"array"][indexPath.row][@"title"] containsString:@"行程"] || [self.tableList[indexPath.section][@"array"][indexPath.row][@"title"] containsString:@"驾车"]) {
        return (SCREEN_WIDTH-32)*0.3838+74;
    }else{
        return 62;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 64;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return CGFLOAT_MIN;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIButton *header = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 64)];
    header.backgroundColor = LightBGColor;
        
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 4, SCREEN_WIDTH, header.height-4)];
    view.backgroundColor = RealWhiteColor;
    [header addSubview:view];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(16, 4, SCREEN_WIDTH/2-16, header.height-4)];
    label.font = REAL_MEDIUM_FONT(14);
    label.textColor = RealBlackColor;
    NSString *date = [NSString stringWithFormat:@"%@",[self compareCurrentTimeWithDate:self.tableList[section][@"date"]]];
    label.text = date;
    [header addSubview:label];
   
    UILabel *subLabel = [[UILabel alloc] initWithFrame:CGRectMake(SCREEN_WIDTH/2, label.y, SCREEN_WIDTH/2-43, label.height)];
    subLabel.font = DEFAULT_FONT(14);
    subLabel.textColor = GraryLightColor;
    subLabel.textAlignment = NSTextAlignmentRight;
    subLabel.text = [NSString stringWithFormat:@"共 %lu 段行程",(unsigned long)[self.tableList[section][@"array"] count]];
    if ([self.tableList[section][@"isShow"] boolValue]) {
        subLabel.hidden = YES;
    }else{
        subLabel.hidden = NO;
    }
    [header addSubview:subLabel];
        
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH-(header.height-4), label.y, header.height-4, label.height)];
    button.userInteractionEnabled = NO;
    [button setImage:[UIImage imageNamed:[self.tableList[section][@"isShow"] boolValue]?@"icon_down":@"icon_more"] forState:UIControlStateNormal];
    [header addSubview:button];
    
    [[header rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        if ([self.tableList[section][@"isShow"] boolValue]) {
            [self.tableList[section] setValue:@(0) forKey:@"isShow"];
        }else{
            [self.tableList[section] setValue:@(1) forKey:@"isShow"];
        }
        [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:UITableViewRowAnimationFade];
    }];
            
    return header;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 0)];
    view.layer.masksToBounds = YES;
    view.backgroundColor = RealWhiteColor;
    return view;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self.tableList[indexPath.section][@"array"][indexPath.row][@"title"] containsString:@"行程"] || [self.tableList[indexPath.section][@"array"][indexPath.row][@"title"] containsString:@"驾车"]) {
        NSString *cellIdentifier = @"TrackMapTableViewCell";
        TrackMapTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (cell == nil) {
            cell = [[TrackMapTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        }
        [cell loadWithInfo:self.tableList[indexPath.section][@"array"][indexPath.row]];
        if ([self.tableList[indexPath.section][@"array"][indexPath.row][@"image"] isKindOfClass:[UIImage class]]) {
            [cell.imgView setImage:self.tableList[indexPath.section][@"array"][indexPath.row][@"image"]];
        }else{
            [cell.imgView setImage:nil];
            [self drawMapImageWithInfo:self.tableList[indexPath.section][@"array"][indexPath.row]];
        }
        return cell;
    }else{
        NSString *cellIdentifier = @"TrackStaticTableViewCell";
        TrackStaticTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (cell == nil) {
            cell = [[TrackStaticTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        }
        [cell loadWithInfo:self.tableList[indexPath.section][@"array"][indexPath.row]];
        cell.TrackStaticRegionBlock = ^(CLLocationCoordinate2D aCoordinate) {
            RegionSettingViewController *vc = [[RegionSettingViewController alloc] init];
            vc.groupInfo = self.groupInfo;
            vc.aCoordinate = aCoordinate;
            [self.viewContainingController.navigationController pushViewController:vc animated:YES];
        };
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.MemberTrackClickBlock) {
        NSMutableDictionary *info = [NSMutableDictionary dictionaryWithDictionary:self.tableList[indexPath.section][@"array"][indexPath.row]];
        [info setValue:_info[@"nickName"] forKey:@"nickName"];
        self.MemberTrackClickBlock(info);
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView==_tableView) {
        self.bgView.y = self.height-orginHeight-scrollView.contentOffset.y+121;
        if (self.bgView.y<0) {
            self.bgView.y = 0;
        }
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (scrollView==_tableView) {
        if (scrollView.contentOffset.y<0) {
            [self dismiss];
        }
    }
}

- (void)reloadViewWithTableList:(NSMutableArray *)tableList
{
    [self.tableView.mj_footer endRefreshing];
    self.time.text = [XDXTimeTool compareCurrentTimeWithDate:_info[@"timestamp"]];
    if (tableList.count>0) {
        self.tableList = [NSMutableArray array];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyyMMdd"];
        dateFormatter.locale = [NSLocale systemLocale];
        dateFormatter.calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierISO8601];
        NSInteger timeInterval = [XDXTimeTool getNowTimeTimestamp].integerValue;
        if ([self.groupInfo[@"membership"] isKindOfClass:[NSDictionary class]]) {
            // 亲密会员黄金会员看30天轨迹，白银会员看15天轨迹
            if ([self.groupInfo[@"membership"][@"planType"] integerValue]==1 || [self.groupInfo[@"membership"][@"planType"] integerValue]==3) {
                timeInterval = timeInterval-(29*86400);
            }else{
                timeInterval = timeInterval-(14*86400);
            }
        }else{
            timeInterval = timeInterval-86400;
        }
        NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeInterval];
        NSString *target = [dateFormatter stringFromDate:date];
        
        for (NSDictionary *dic in tableList) {
            if ([[dic[@"date"] substringToIndex:10] stringByReplacingOccurrencesOfString:@"-" withString:@""].integerValue>=target.integerValue) {
                [self.tableList addObject:dic];
                if ([[dic[@"date"] substringToIndex:10] stringByReplacingOccurrencesOfString:@"-" withString:@""].integerValue==target.integerValue){
                    [self initFooterPayView];
                }
            }else{
                [self initFooterPayView];
            }
        }
    }else{
        self.tableList = [NSMutableArray array];
    }
    
    if (self.tableList.count>0) {
        if ([self.tableList.firstObject[@"array"] count]>0) {
            NSDictionary *dic = [self.tableList.firstObject[@"array"] firstObject];
            if ([dic[@"array"] count]>0) {
                NSDictionary *dictionary = [dic[@"array"] lastObject];
                NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
                [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
                dateFormatter.locale = [NSLocale systemLocale];
                dateFormatter.calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierISO8601];
                NSDate *firstDate = [dateFormatter dateFromString:[dictionary[@"create_time"] substringToIndex:19]];
                NSInteger firstSecond = [firstDate timeIntervalSince1970];
                            
                NSInteger lastSecond = [[XDXTimeTool getNowTimeTimestamp] integerValue];

                NSInteger second = lastSecond-firstSecond;
                if (second/3600.0>1) {
                    _nickTime.text = [NSString stringWithFormat:@"%ld小时%ld分钟前更新",(long)(second/3600),(long)(second%3600/60)];
                }else{
                    _nickTime.text = [NSString stringWithFormat:@"%@分钟前更新",[NSString stringWithFormat:@"%ld",(long)(second/60)]];
                }
            }
        }
    }
    
    [self.tableView reloadData];
}

- (void)initFooterPayView
{
    if (![self.groupInfo[@"membership"] isKindOfClass:[NSDictionary class]]) {
        UIView *footer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_WIDTH*1.589)];        
        
        UIView *bg = [[UIView alloc] initWithFrame:CGRectMake(0, footer.height, SCREEN_WIDTH, SCREEN_HEIGHT)];
        bg.backgroundColor = CashFooterColor;
        [footer addSubview:bg];
                
        UIImageView *img = [[UIImageView alloc] initWithFrame:footer.bounds];
        img.userInteractionEnabled = YES;
        img.image = [UIImage imageNamed:@"track_member"];
        [footer addSubview:img];
        
        // 从小到上布局
        UILabel *groupInfo = [[UILabel alloc] initWithFrame:CGRectMake(16, img.height-45, img.width-32, 16)];
        groupInfo.textAlignment = NSTextAlignmentCenter;
        groupInfo.textColor = [RealWhiteColor colorWithAlphaComponent:0.65];
        groupInfo.font = DEFAULT_FONT(12);
        groupInfo.text = [NSString stringWithFormat:@"为 “%@” 开通",self.groupInfo[@"name"]];
        [img addSubview:groupInfo];
        
        UIButton *pay = [[UIButton alloc] initWithFrame:CGRectMake(16, groupInfo.y-64, img.width-32, 54)];
        pay.layer.masksToBounds = YES;
        [pay.layer setCornerRadius:27];
        pay.backgroundColor = NormalMainColor;
        [pay setTitleColor:RealWhiteColor forState:UIControlStateNormal];
        [pay.titleLabel setFont:MEDIUM_FONT(16)];
        [pay setTitle:@"开通会员" forState:UIControlStateNormal];
        [img addSubview:pay];
        [[pay rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            CashViewController *vc = [[CashViewController alloc] init];
            vc.groupInfo = self.groupInfo;
            [self.viewContainingController.navigationController pushViewController:vc animated:YES];
        }];
        
        UIView *infoView = [[UIView alloc] initWithFrame:CGRectMake(0, pay.y-162, img.width, 136)];
        [img addSubview:infoView];
        
        UILabel *subTitle = [[UILabel alloc] initWithFrame:CGRectMake(16, 0, infoView.width-32, 24)];
        subTitle.textColor = [RealWhiteColor colorWithAlphaComponent:0.75];
        subTitle.font = DEFAULT_FONT(14);
        subTitle.text = @"随时了解家庭成员旅途的情况，开通会员解锁更长轨迹、更多安全功能。";
        subTitle.numberOfLines = 0;
        [subTitle sizeToFit];
        [infoView addSubview:subTitle];
        
        UILabel *current = [[UILabel alloc] initWithFrame:CGRectMake(16, subTitle.maxY+32, 82, 24)];
        current.textColor = [RealWhiteColor colorWithAlphaComponent:0.6];
        current.font = DEFAULT_FONT(14);
        current.text = @"当前计划";
        [infoView addSubview:current];
        
        UILabel *currentDetail = [[UILabel alloc] initWithFrame:CGRectMake(16, current.maxY+8, 82, 24)];
        currentDetail.textColor = [RealWhiteColor colorWithAlphaComponent:0.6];
        currentDetail.font = DEFAULT_FONT(14);
        currentDetail.text = @"2天历史记录";
        [infoView addSubview:currentDetail];
        
        UILabel *member = [[UILabel alloc] initWithFrame:CGRectMake(infoView.width-102, subTitle.maxY+32, 58, 24)];
        member.font = REAL_MEDIUM_FONT(14);
        member.textAlignment = NSTextAlignmentRight;
        [infoView addSubview:member];
        
        UIImageView *memberImg = [[UIImageView alloc] initWithFrame:CGRectMake(member.maxX+6, subTitle.maxY+33, 22, 22)];
        [infoView addSubview:memberImg];
        
        UILabel *locationCount = [[UILabel alloc] initWithFrame:CGRectMake(infoView.width-118, memberImg.maxY+8, 102, 24)];
        locationCount.font = REAL_MEDIUM_FONT(14);
        locationCount.textAlignment = NSTextAlignmentRight;
        locationCount.textColor = RealWhiteColor;
        locationCount.text = @" 30天历史记录";
        [infoView addSubview:locationCount];
            
        if ([_groupInfo[@"memberCount"] integerValue]<=2) {
            member.text = @"亲密会员";
            member.textColor = CloseColor;
            memberImg.image = [UIImage imageNamed:@"icon_close"];
        }else{
            member.text = @"黄金会员";
            member.textColor = GoldColor;
            memberImg.image = [UIImage imageNamed:@"icon_gold"];
        }
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(16, infoView.y-46, SCREEN_WIDTH-32, 30)];
        label.font = MEDIUM_FONT(20);
        label.textColor = RealWhiteColor;
        label.text = @"历史轨迹记录";
        [img addSubview:label];
        
        UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(16, label.y-42, SCREEN_WIDTH-32, 36)];
        title.font = MEDIUM_FONT(28);
        title.textColor = RealWhiteColor;
        title.text = @"解锁 30 天";
        [img addSubview:title];
        
        
        
        _tableView.tableFooterView = footer;
    }else{
        _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 10)];
    }
}

- (NSString *)compareCurrentTimeWithDate:(NSString *)aDate
{
    NSString *string = aDate;

    NSString *result;
    if ([[string substringToIndex:10] isEqualToString:[[XDXTimeTool currentDate] substringToIndex:10]]) {
        result = @"今天";
    }else{
        NSInteger yesTimetamp = [XDXTimeTool getNowTimeTimestamp].integerValue-86400;
        NSDate *date = [NSDate dateWithTimeIntervalSince1970:yesTimetamp];
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        NSString *dateStr = [formatter stringFromDate:date];
        
        if ([[dateStr substringToIndex:10] isEqualToString:[aDate substringToIndex:10]]) {
            result = @"昨天";
        }else{
            result = [string substringWithRange:NSMakeRange(5, 5)];
        }
    }
    return  result;
}

- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.height, SCREEN_WIDTH, self.height-NAVHEIGHT) style:UITableViewStylePlain];
        _tableView.separatorStyle  = UITableViewCellSeparatorStyleNone;
        _tableView.estimatedRowHeight = 0;
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        if (@available(iOS 15.0, *)) {
            _tableView.fillerRowHeight = 0;
            _tableView.sectionHeaderTopPadding = 0;
        }
        _tableView.layer.masksToBounds = NO;
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            if (!self.tableView.tableFooterView) {
                if (self.MemberTrackMoreBlock) {
                    self.MemberTrackMoreBlock();
                }
            }else{
                [self.tableView.mj_footer endRefreshing];
            }
            
        }];
    }
    return _tableView;
}

@end
